package com.dji.sample.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.LinkedBlockingQueue;


@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("thumbnailExecutor")
    public Executor thumbnailExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,
                20,
                120L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("thumbnail-" + thread.getId());
                    thread.setDaemon(false);
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        
        executor.allowCoreThreadTimeOut(true);
        
        return executor;
    }

    @Bean("asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,
                20,
                300L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(200),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("async-" + thread.getId());
                    thread.setDaemon(false);
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        
        executor.allowCoreThreadTimeOut(true);
        
        return executor;
    }
}